package com.tuju.jetpackfirstdemo.ui.video;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.tuju.jetpackfirstdemo.R;
import com.tuju.jetpackfirstdemo.utils.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class VideoActivity extends AppCompatActivity {

    private VideoView videoView;
    private List<Uri> mVideoList = new ArrayList<>();
    private int mCurrPlayIndex = 0;//当前播放视频

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        initView();
        initData();
    }

    private void initView() {
        videoView = findViewById(R.id.video);
    }

    private void initData() {
        checkPermissionForNormal(Manifest.permission.WRITE_EXTERNAL_STORAGE);//检查读取内存权限
    }

    /**
     * 开始播放
     */
    private void start() {
        videoView.setVideoURI(mVideoList.get(mCurrPlayIndex));
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        videoView.start();
                    }
                }, 200);
            }
        });
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                playNextVideo();
            }
        });
    }

    private void reStar(){
        videoView.pause();
        videoView.setVideoURI(mVideoList.get(mCurrPlayIndex));
        videoView.start();
    }

    /**
     * 停止播放
     */
    private void stop() {
        videoView.pause();
    }

    private void playNextVideo() {
        mCurrPlayIndex += 1;
        if (mCurrPlayIndex >= mVideoList.size()) {
            mCurrPlayIndex = 0;
        }
        reStar();
    }

    public void jumpVideo2(View view) {
        startActivity(new Intent(this,Video2Activity.class));
    }

    /**
     * 读取文件
     */
    private void readFile() {
        File flagFile = FileUtil.getMkdirFile();
        if (flagFile == null) {
            Toast.makeText(this, "没有视频!", Toast.LENGTH_SHORT).show();
            return;
        }
        for (File childFile :
                flagFile.listFiles()) {
            Log.i("yanze", "FileName: " + childFile.getName());
            if (childFile.getName().endsWith(".mp4")) {
                Log.i("yanze", "----------------->已添加 ");
                Uri uri = Uri.parse(childFile.getAbsolutePath());//将路径转换成uri
                mVideoList.add(uri);
            }
        }
        if (mVideoList.isEmpty()) {
            Toast.makeText(this, "文件夹下没有视屏，请将视屏文件放入" + flagFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
        } else {
            Log.i("yanze", "共有文件 ");
            start();
        }
    }

    //检查权限 动态申请授权
    public void checkPermissionForNormal(String permission) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                readFile();
            }
            return;
        }
        //判断是否授权拍照  Manifest.permission.CAMERA
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            //如果之前申请,并且用户点击了拒绝,会返回true
            String msg = "";
            int code = 101;
            if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                code = 101;
            }
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请给予应用读取内存权限！", Toast.LENGTH_SHORT).show();
            } else {
                //去申请权限
                ActivityCompat.requestPermissions(this, new String[]{permission}, code);
            }
        } else {
            if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                readFile();
            }
        }
    }

    //授权回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 101:
                if (grantResults.length > 0) {
                    readFile();
                } else {
                    Toast.makeText(this, "请给予应用读取内存权限！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
